/**
 * Created by tanbingqin on 2019/8/16.
 */
import { messages } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import { Button, Form, Switch, Icon, message, Row, Col } from 'antd'
const FormItem = Form.Item;
import LanguageInput from 'components/template/language-input/language-input'
import Chooser from 'components/chooser'
import errorMessage from 'share/errorMessage';
import EmailNotificationService from 'containers/setting/email-notification/email-notification.service'

class NewTemplate extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      template: {
        businessDescribe: '',
        title: '',
        content: '',
        businessDescribeI18n: null,
        titleI18n: null,
        contentI18n: null
      },
      titleTagList: [
        {label: messages('setting.key2163')/*单据类型(DocTyp)*/, value: '#DocTyp#', key: 'DocTyp'},
        {label: messages('setting.key2164')/*单据编号(DocNo)*/, value: '#DocNo#', key: 'DocNo'}
      ],
      contentTagList: [
        {label: messages('setting.key2163')/*单据类型(DocTyp)*/, value: '#DocTyp#', key: 'DocTyp'},
        {label: messages('setting.key2164')/*单据编号(DocNo)*/, value: '#DocNo#', key: 'DocNo'},
        {label: messages('setting.key2165')/*单据事由(DocRea)*/, value: '#DocRea#', key: 'DocRea'},
        {label: messages('setting.key2166')/*单据金额(DocAmo)*/, value: '#DocAmo#', key: 'DocAmo'},
        {label: messages('setting.key2167')/*提交日期(SubDate)*/, value: '#SubDate#', key: 'SubDate'},
        {label: messages('setting.key2168')/*提交人(SubPeop)*/, value: '#SubPeop#', key: 'SubPeop'},
        {label: messages('setting.key2169')/*单据链接(DocLink)*/, value: '#DocLink#', key: 'DocLink'}
      ]
    }
  }

  componentDidMount(){}

  componentWillReceiveProps(nextProps) {
    const { templateVisible, form } = this.props;
    if (!templateVisible && nextProps.templateVisible) {
      if (nextProps.record) {
        this.setState({
          template: {
            businessDescribe: nextProps.record.businessDescribe,
            title: nextProps.record.title,
            content: nextProps.record.content,
            businessDescribeI18n: JSON.parse(JSON.stringify(nextProps.record.i18n.businessDescribe)),
            titleI18n: JSON.parse(JSON.stringify(nextProps.record.i18n.title)),
            contentI18n: JSON.parse(JSON.stringify(nextProps.record.i18n.content))
          }
        });
      }
    }
    if (templateVisible && !nextProps.templateVisible) {
      form.resetFields();
      this.setState({
        template: {
          businessDescribe: '',
          title: '',
          content: '',
          businessDescribeI18n: null,
          titleI18n: null,
          contentI18n: null
        }
      });
    }
  };

  onCancel = () => {
    this.props.close();
  };

  handleSave = () => {
    const { form, close, record } = this.props;
    const { template } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (!template.businessDescribe) {
          message.error(messages('setting.key2170')/*请输入业务描述*/);
          return;
        }
        if (!template.title) {
          message.error(messages('setting.key2171')/*请输入邮件标题*/);
          return;
        }
        if (!template.content) {
          message.error(messages('setting.key2172')/*请输入邮件正文*/);
          return;
        }
        let params = {};
        params.id = record ? record.id : undefined;
        params.i18n = {};
        params.businessDescribe = template.businessDescribe;
        params.i18n.businessDescribe = template.businessDescribeI18n;
        params.title = template.title;
        params.i18n.title = template.titleI18n;
        params.content = template.content;
        params.i18n.content = template.contentI18n;
        params.valid = values.valid;
        if (values.forms && values.forms.length) {
          params.visibleFormScope = 2;//部分
          params.formOIDList = [];
          values.forms.map(form => {
            params.formOIDList.push(form.formOID);
          });
        } else {
          params.visibleFormScope = 1;//通用
        }
        if (values.companies && values.companies.length) {
          params.visibleCompanyScope = 2;//部分
          params.companyOIDList = [];
          values.companies.map(company => {
            params.companyOIDList.push(company.companyOID);
          });
        } else {
          params.visibleCompanyScope = 1;//通用
        }
        this.setState({loading: true});
        EmailNotificationService.addEditTemplate(params).then((response) => {
          this.setState({loading: false});
          close(true);
        }).catch((e) => {
          errorMessage(e.response);
          this.setState({loading: false});
        });
      }
    });
  };

  handleLanguageInput = (name, i18n, attr) => {
    let { template } = this.state;
    template[attr] = name;
    template[attr + 'I18n'] = i18n;
    this.setState({template});
  };

  //type title标题 content正文
  renderTagList = (type) => {
    const { titleTagList, contentTagList } = this.state;
    let tagList = type === 'title' ? titleTagList : contentTagList;
    return (
      <div style={{lineHeight: '20px'}}>
        {tagList.map(tag => {
          return (
            <span
              style={{color: '#0092da', cursor: 'pointer', display: 'inline-block', marginRight: 8}}
              onClick={() => this.addTag(tag.value, type === 'title' ? 100 : 1000, type)}
            >
              {tag.label}
            </span>
          )
        })}
      </div>
    )
  };

  //type title标题 content正文
  addTag = (txt, inpLength, type) => {
    const { template } = this.state;
    const { setFieldsValue } = this.props.form;
    const { language: currentLanguage, languageList } = this.props;
    template[type] = template[type] + txt;
    if(template[type].length > inpLength){
      message.warn(messages('components.key665',{arg1: inpLength}/*字数超过限制,自动截取前 {arg1} 个*/));
      template[type] = template[type].substring(0, inpLength);
    }
    let i18nKey = type === 'title' ? 'titleI18n' : 'contentI18n';
    if (template[i18nKey]) {
      template[i18nKey].map(item => {
        if (item.language.toLowerCase() === currentLanguage.code.toLowerCase()) {
          item.value = template[type];
        }
      });
    } else {
      let typeI18n = [];
      languageList.map(language => {
        typeI18n.push({
          language: language.code.toLowerCase(),
          value: language.code.toLowerCase() === currentLanguage.code.toLowerCase() ? template[type] : ''
        });
      });
      template[i18nKey] = typeI18n;
    }
    this.setState({template});
  };

  //获取多语言输入框的字符长度
  getInpRule = (num) => {
    const { languageList } = this.props;
    let inpRule = [];
    languageList.map(language => {
      inpRule.push({
        length: num,
        language: language.code.toLowerCase()
      });
    });
    return inpRule;
  };

  //编辑状态初始化适用公司数据
  getInitCompany = () => {
    const { record } = this.props;
    return record.visibleCompanyScope === 1 ? undefined : record.customCompanyRelationResps;
  };

  //编辑状态初始化适用表单数据
  getInitForm = () => {
    const { record } = this.props;
    return record.visibleFormScope === 1 ? undefined : record.customFormRelationResps;
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, template } = this.state;
    const { record, tenantMode } = this.props;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 15, offset: 1}
    };
    return (
      <div>
        <Form>
          <Row style={{marginBottom: 32}}>
            <Col span={6} style={{lineHeight: '32px', textAlign: 'right'}}>
              <span style={{display: 'inline-block', marginRight: 4, color: '#FF0000', fontFamily: 'SimSun'}}>*</span>{messages('setting.key1186')/*业务描述*/}：
            </Col>
            <Col span={15} offset={1}>
              <LanguageInput
                key="businessDescribe"
                nameChange={(value, i18n) => this.handleLanguageInput(value, i18n, 'businessDescribe')}
                width={'100%'}
                name={template.businessDescribe}
                inpRule={this.getInpRule(100)}
                placeholder={messages('common.max.characters.length', {max: 100})}
                isEdit
                i18nName={template.businessDescribeI18n}
                disabled={!tenantMode}
              />
            </Col>
          </Row>
          <FormItem {...formItemLayout} label={messages('common.column.status')/*状态*/}>
            {getFieldDecorator('valid', {
              valuePropName: 'checked',
              initialValue: record ? record.valid : true
            })(
              <Switch checkedChildren={<Icon type="check"/>} unCheckedChildren={<Icon type="cross"/>} disabled={!tenantMode} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key2160')/*适用表单*/}>
            {getFieldDecorator('forms', {
              initialValue: record ? this.getInitForm() : undefined
            })(
              <Chooser
                showNumber
                type="available_forms"
                valueKey="formOID"
                labelKey="formName"
                listExtraParams={{
                  valid: true
                }}
                placeholder={messages('setting.key1037'/*通用*/)}
                disabled={!tenantMode}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key730')/*适用公司*/}>
            {getFieldDecorator('companies', {
              initialValue: record ? this.getInitCompany() : undefined
            })(
              <Chooser
                type="available_company"
                valueKey="companyOID"
                labelKey="name"
                placeholder={messages('setting.key1037'/*通用*/)}
                disabled={!tenantMode}
              />
            )}
          </FormItem>
          <Row style={{marginBottom: 32}}>
            <Col span={6} style={{lineHeight: '20px', textAlign: 'right'}}>
              <span style={{display: 'inline-block', marginRight: 4, color: '#FF0000', fontFamily: 'SimSun'}}>*</span>{messages('setting.key495')/*邮件标题*/}：
            </Col>
            <Col span={15} offset={1}>
              {tenantMode && this.renderTagList('title')}
              <LanguageInput
                nameChange={(value, i18n) => this.handleLanguageInput(value, i18n, 'title')}
                width={'100%'}
                name={template.title}
                inpRule={this.getInpRule(100)}
                placeholder={messages('common.max.characters.length', {max: 100})}
                isEdit
                i18nName={template.titleI18n}
                disabled={!tenantMode}
              />
            </Col>
          </Row>
          <Row style={{marginBottom: 32}}>
            <Col span={6} style={{lineHeight: '20px', textAlign: 'right'}}>
              <span style={{display: 'inline-block', marginRight: 4, color: '#FF0000', fontFamily: 'SimSun'}}>*</span>{messages('setting.key496')/*邮件正文*/}：
            </Col>
            <Col span={15} offset={1}>
              {tenantMode && this.renderTagList('content')}
              <LanguageInput
                nameChange={(value, i18n) => this.handleLanguageInput(value, i18n, 'content')}
                width={'100%'}
                name={template.content}
                inpRule={this.getInpRule(1000)}
                placeholder={messages('common.max.characters.length', {max: 1000})}
                isEdit
                textArea
                i18nName={template.contentI18n}
                disabled={!tenantMode}
              />
            </Col>
          </Row>
        </Form>
        {tenantMode && (
          <div className="slide-footer">
            <Button type="primary" onClick={this.handleSave} loading={loading}>{messages('common.ok')/*确定(*/}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')/*返回(*/}</Button>
          </div>
        )}
      </div>
    )
  }
}

NewTemplate.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    language: state.main.language,
    languageList: state.login.languageList,
    tenantMode: state.main.tenantMode
  }
}

const WrappedNewTemplate = Form.create()(NewTemplate);

export default connect(mapStateToProps)(WrappedNewTemplate);
